package com.guodefu.demo.config;

import org.springframework.cache.interceptor.CacheAspectSupport;
import org.springframework.cache.interceptor.CacheOperation;
import org.springframework.cache.interceptor.CacheOperationInvoker;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Collection;

@Component
public class CustomCacheAspect extends CacheAspectSupport {

    private final ApplicationContext applicationContext;

    public CustomCacheAspect(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {

        // 获取 CacheOperationContext
//        CacheOperationInvocationContext<?> context = getOperationContext(invoker, method, args, target);

        // 检查是否存在 CustomCacheable 注解
        CustomCacheable customCacheable = method.getAnnotation(CustomCacheable.class);
        if (customCacheable != null) {
            String ttlValue = customCacheable.ttl();
            Class<? extends TtlStrategy> ttlStrategy = customCacheable.type();
            TtlStrategy strategy = applicationContext.getBean(ttlStrategy);
            Duration ttl = parseTtl(ttlValue, strategy);

            Collection<CacheOperation> cacheOperations = getCacheOperationSource().getCacheOperations(method, target.getClass());
            // 从 CacheManager 获取对应的 Cache 对象
//            Cache cache = getCache(context);
//            if (cache instanceof CustomRedisCache) {
//                Object key = SimpleKeyGenerator.generateKey(args);
//                return ((CustomRedisCache) cache).putWithCustomTtl(key, invoker, ttl);
//            }
            System.out.println("aa");
        }

        return super.execute(invoker, target, method, args);
    }

//    private Cache getCache(CacheOperationInvocationContext<?> context) {
//        // 获取 CacheManager 并查找与 @CustomCacheable 注解中的 value 对应的 Cache
//        Collection<Cache> caches = getCacheManager().getCacheNames();
//        String cacheName = context.getOperation().getCacheNames().iterator().next();
//        return getCacheManager().getCache(cacheName);
//    }

    private Duration parseTtl(String ttlValue, TtlStrategy strategy) {
        if (ttlValue.isEmpty()) {
            return Duration.ZERO;
        }
        return Duration.ofSeconds(strategy.getTtl(ttlValue));
    }
}

